﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using MyAnimelistRecommender.DataObject;

namespace MyAnimelistRecommender.Helper
{
    internal class GroupingHelper
    {
        private static bool[] _lookup;

        static GroupingHelper()
        {
            _lookup = new bool[65535];
            for (char c = '0'; c <= '9'; c++) _lookup[c] = true;
            for (char c = 'A'; c <= 'Z'; c++) _lookup[c] = true;
            for (char c = 'a'; c <= 'z'; c++) _lookup[c] = true;
        }

        public static string RemoveSpecialCharacters(string str)
        {
            char[] buffer = new char[str.Length];
            int index = 0;
            foreach (char c in str)
            {
                if (_lookup[c])
                {
                    buffer[index] = c;
                    index++;
                }
            }
            return new string(buffer, 0, index);
        }

        public static void CreateGroups(List<Anime> animes)
        {
            string[] names = animes.Select(x => RemoveSpecialCharacters(x.Title)).ToArray();
            Dictionary<int, List<int>> indexes = new Dictionary<int, List<int>>();

            for (int i = 0; i < names.Length; i++)
            {
                for (int y = 0; y < names.Length; y++)
                {
                    if (names[y].Contains(names[i]) && names[y] != names[i])
                    {
                        if (indexes.ContainsKey(i))
                            indexes[i].Add(y);
                        else
                            indexes.Add(i, new List<int>() { y });
                    }
                }
            }

            Debug.WriteLine("-------------------");
            foreach (KeyValuePair<int, List<int>> kv in indexes)
            {
                Debug.Write(animes[kv.Key].Title + ": ");
                kv.Value.ForEach(x => { Debug.Write(animes[x].Title + ", "); });
                Debug.WriteLine("");

                animes[kv.Key].GroupTitle = animes[kv.Key].Title;
                kv.Value.ForEach(x => { animes[x].GroupTitle = animes[kv.Key].Title; });
            }
        }
    }
}